import React, { Component } from 'react';
import { Select, message, Button, Icon, Table, Tooltip, DatePicker } from 'antd';
import detailsStyle from './detail.module.sass'
import { _getReturnOrg, _getCompareRateRisk, _historyRate, _getWeekRate, _getProCorrelation, _getCompareList, _getCorrelationTable, _getHistoryInvest, _getRankingData} from '../../apis/details/performance_api'
import { areaColors, chartsColors, options1, options2, options3, rankColumns, historyColumns, monthColumns } from './performance_data'
import PerformanceSearch from './component/performance_search'
import AddCompanyModal from './component/add_product_modal'
import HeaderTitle from '../common_title/common_header_title'
import CommonCharts from '../common_chart/index'
import RiskTable from './component/risk_table'

import axios from '../../Utils/axios'
import url from 'url'


const Option = Select.Option;
const { query } = url.parse(window.location.href, true)
export default class Performance extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
        headerData:{},
        dataSource: [],
        monthData: [],
        selectData: [],
        corData: [],
        corColumns: [],
        investData: [],
        rankData: [],
        defaultCorrelation: ['000300.SH', '000905.SH', '000016.SH', '000906.SH', '000001.SH', '399006.SZ'],
        isCenter: true,
        indicator: 'return',
        rankType: '2',
        token: "88d34ede-9302-4b5a-8701-4e940d425d9b"
    }
    this.echarts1 = ''
    this.echarts2 = ''
    this.echarts3 = ''
    this.echarts4 = ''
    
  }
    
    // 起点对齐
    changeCheckStatus = (e) => {
        console.log('起点对齐', e)
        this.setState({isCenter: e})
    }

    // 导出
    exportExcelFiles = (title) => {
        console.log('export', title)
        // const param = Object.assign(this.state.baseParams, { fundIds: this.state.fundId, startLine: this.state.startLine })
        // this.setState({baseParams: param})
        const param = {
                navType: 'n_added_nav',
                compareRule: '000300.SH',
                dateRange: '',
                statPeriod: 'year',
                fundIds: 'JR000001',
                startLine: 1
        }
        this.commonExportExcel('收益走势图','returnCal', param)
    }


    //导出excel调接口
    async commonExportExcel(name,  chartCode, params) {
        let wordOptions = [];
        wordOptions.push({
            moduleName: '业绩表现',
            moduleContent:
            [{
                tableOrChartName: name,
                tableOrChartCode: chartCode,
                tableOrChartParams: params
            }]
        })

        let data = await axios({
            method: 'POST',
            url: '/hsApi/hszcpz/exportExcel/produceExcelFile',
            data: JSON.stringify({
                // token: cookie.get('token'),
                token: "88d34ede-9302-4b5a-8701-4e940d425d9b",
                modules: wordOptions,
                fundName: query.name,
            })
        })

        if (data.status === 'success') {
            try {
                let json = data
                // const warnInfo = Object.keys(data).includes('warnInfo0');
                if (json.status === 'success' && json.hasData === 'yes' ) {
                    // const url = `${process.env.REACT_APP_EXPORT_URL}/hsApi/hszcpz/exportExcel/exportExcelFile?token=${cookie.get('token')}&fileName=${json.fileName}&fileDate=${json.fileDate}`
                    const url = `${process.env.REACT_APP_EXPORT_URL}/hsApi/hszcpz/exportExcel/exportExcelFile?token="88d34ede-9302-4b5a-8701-4e940d425d9b"&fileName=${json.fileName}&fileDate=${json.fileDate}`
                    window.location.href = url
                }
            } catch (err) {
                message.error('解析出错')
            }
        } else {
            message.info('获取数据失败')
        }
    }

    componentDidMount() {
        this.getEcharts()
    }

    async getEcharts(params) {
        const baseparams = {
            navType: 'n_added_nav',
            compareRule: '000300.SH',
            dateRange: '',
            statPeriod: 'year',
            startDateVal: null,
            endDateVal: null,
            startLine: 0,
            fundIds: 'JR000001',
            token: "88d34ede-9302-4b5a-8701-4e940d425d9b"
        }

        params = Object.assign(baseparams, params)
        // 收益，回撤走势图
        const returnOrgData = await _getReturnOrg(params)
        if (returnOrgData && typeof returnOrgData === 'object') {
            const keys = returnOrgData.hasOwnProperty('name_list') ? returnOrgData.name_list : [];
            const xData = returnOrgData.hasOwnProperty('figure') ? returnOrgData.figure.x_axis : []
            let proLineName = [], lineSeries=[],areaSeries= [];
            
            keys.forEach((item, index) => {
                let lineDatas = [], areaDatas = [];
                proLineName.push(item)
                returnOrgData.figure.y_axis.return_fig[item].forEach(item => {
                        if (item !== '') {
                            lineDatas.push(isNaN(item) ? item : parseFloat(item * 100).toFixed(2))
                        } else {
                            lineDatas.push('--')
                        }

                })
                returnOrgData.figure.y_axis.drawdown_fig[item].map((item) => {
                    if (item !== '') {
                        areaDatas.push(isNaN(item) ? item : parseFloat(item * 100).toFixed(2))
                    } else {
                        areaDatas.push('--')
                    }

                })
                areaSeries.push({
                    name: item,
                    type: 'line',
                    symbol: false,
                    symbolSize: 0,
                    lineStyle: {
                        normal: {
                            shadowColor: 'rgba(0, 0, 0, 0.2)',
                            shadowOffsetY: 2,
                            shadowOffsetX: 2,
                            shadowBlur: 5
                        }
                    },
                    areaStyle: {
                        color: areaColors[index],
                        opacity: 1
                    },
                    itemStyle: {
                        normal: {
                            color: chartsColors[index],
                        }
                    },
                    data: areaDatas || []
                })
                lineSeries.push({
                    name: item,
                    type: 'line',
                    symbol: false,
                    symbolSize: 0,
                    lineStyle: {
                        normal: {
                            shadowColor: 'rgba(0, 0, 0, 0.2)',
                            shadowOffsetY: 2,
                            shadowOffsetX: 2,
                            shadowBlur: 5
                        }
                    },
                    itemStyle: {
                        normal: {
                            color: chartsColors[index],
                        }
                    },
                    data: lineDatas || []
                })
            })
            options1.legend.data = keys
            options1.series = lineSeries
            options1.xAxis.data = xData
            options2.legend.data = keys
            options2.series = areaSeries
            options2.xAxis.data = xData
            this.refs.lineChart.setOpitions(options1);
            this.refs.areaChart.setOpitions(options2);
            this.echarts1 = document.getElementById('lineChart')
            this.echarts2 = document.getElementById('areaChart')
            
        }
        // 收益-风险指标图
        this.getRateRiskData(params);
        // 月度收益率
        this.getHistoryRateData(params)
        // 周收益率分布
        this.getWeekRateData(params)
        // 产品相关性
        this.getCorrelationData(params)
        this.getCorData(params)
        // 历史收益能力
        this.getHistoryInvestData(params)
    }

    async getHeadSecData(data) {
        await this.setState({ headerData: data })
        this.getEcharts(data)
    }
   
    async indicator(value) {
        console.log("indicator", value)
        await this.setState({ indicator: value })
    }
    async rankType (value) {
        await this.setState({ rankType: value })
    }
    async riskTable(val) {
        await this.setState({ compareRule: val })
        const params = {compareRule: val}
        this.getRateRiskData(params)
    }
    async sharpeChange(val) {
        await this.setState({ noRiskReturnRate: val })
        const params = {noRiskReturnRate: val }
        this.getRateRiskData(params)
    }

     // 收益-风险指标
    async getRateRiskData(params) {
        const baseParams = {
            navType: 'n_added_nav',
            compareRule: '000300.SH',
            dateRange: '',
            statPeriod: 'year',
            startDateVal: null,
            endDateVal: null,
            startLine: 0,
            fundIds: 'JR000001',
            noRiskReturnRate: '2.5',
            fundNames: ['鹏华资产-清水源'],
            token: "88d34ede-9302-4b5a-8701-4e940d425d9b"
        }
        params = Object.assign(baseParams, params)
        const rateRiskData = await _getCompareRateRisk(params);
        if (rateRiskData.hasOwnProperty("name_list")) {
            let datas = []
            let data = [rateRiskData];
            const name = rateRiskData.name_list;
            data.forEach((item, index) => {
                let nameSpace = item['name_list']
                let keys = Object.keys(item)

                nameSpace.forEach((its, ind) => {
                    let values = {}
                    values['key'] = ind
                    values['name'] = its
                    keys.forEach(it => {
                        if (it !== 'name_list' && it !== 'id') {
                            values[it] = isNaN(item[it][its]) ? item[it][its] : item[it][its]
                        }
                    })
                    datas.push(values)
                })
            })
            this.setState({ dataSource: datas})
        }
    }

    // 月度收益率
    async getHistoryRateData() {
        const params = {fund_id: "JR000001", token: "88d34ede-9302-4b5a-8701-4e940d425d9b"}
        const data = await _historyRate(params)
        if (data) {
            for (let i = 0; i < data.length; i++) {
                data[i].key = i
            }
            await this.setState({ monthData: data})
        }
    }

    // 周收益率分布
    async getWeekRateData(params) {
        const baseparams = { fundId: "JR000001" }
        params = Object.assign(baseparams, params)
        const data = await _getWeekRate(params)
        let lineData = [], axisData = [];
        if (data && typeof data === 'object') {
            Object.keys(data.kde).map((item, index) => {
                axisData = Object.keys(data.return_dist[item]);
                const lineItemData = data.kde[item].map((items) => !items ? '--' : items * 100)
                lineData.push({
                    name: item,
                    type: 'line',
                    smooth: true,
                    data: lineItemData,
                    symbol: 'none',
                    lineStyle: {
                        color: chartsColors[index],
                        shadowColor: 'rgba(0, 0, 0, 0.2)',
                        shadowOffsetY: 2,
                        shadowOffsetX: 2,
                        shadowBlur: 5
                    }
                })
                lineData.push({
                    name: item,
                    type: 'bar',
                    barGap: 0.1,
                    data: Object.values(data.return_dist[item]),
                    barWidth: '40px',
                    itemStyle: {
                        normal: {
                            color: chartsColors[index]
                        }
                    }
                })
            })
            options3.series = lineData;
            options3.xAxis.data = axisData;
            this.echarts3 = document.getElementById('weekCharts')
            this.refs.weekCharts.setOpitions(options3)
        }
    }
    // 产品相关性柱状图
    async getCorrelationData(params) {
        const baseParams = { fund_id: "JR207118", c_interval: 'year', c_cor_ids: ["000300.SH", "000905.SH", "000016.SH", "000906.SH", "000001.SH", "399006.SZ"], token:"88d34ede-9302-4b5a-8701-4e940d425d9b" }
        const data = await _getProCorrelation(baseParams);
        if (data.productCorrelations && data.productCorrelations.length > 0) {
            let seriesData = [], axisData = [];
            data.productCorrelations.map((item) => {
                seriesData.push(item.nCorrelation);
                axisData.push(item.fundName)
            })
            const series = [{ name: '12', type: 'bar', data: seriesData, barWidth: 30,itemStyle: {
                normal: {
                    color: chartsColors[4]
                }
            } }]
            options1.dataZoom = null;
            options1.series = series;
            options1.xAxis.data = axisData;
            options1.yAxis.min = -100
            options1.yAxis.max = 100
            options1.yAxis.name = "相关性（%）"
            this.echarts4 = document.getElementById('correlationCharts')
            this.refs.correlation.setOpitions(options1)
        }
        const selectData = await _getCompareList({ token: "88d34ede-9302-4b5a-8701-4e940d425d9b" })
        this.setState({selectData: selectData})
    }
    // 产品相关性下拉框多选
    async multipleSelect (val) {
       if (val.length > 6) {
            message.destroy()
            message.info('业绩基准最多只能选取6个')
            return
        }
       await this.setState({
            defaultCorrelation: val
        })
    }
    // 添加对比产品
    addModal = () => {
        this.refs.addCompanyPro.showModal();
    }
    //产品相关性table 
    async getCorData(params) {
        params.fundIds = "JR207118,JR000002,JR000001";
        const baseParams = { fundNames: ["汇鸿汇升星汇旗舰私募证券投资基金", "鹏华资产-长河优势1号A", "鹏华资产-清水源"], startLine: 1}
        params = Object.assign(baseParams, params)
        const data = await _getCorrelationTable(params);
        let dataSource = [], cols = [];
        if (data) {
            const names = data.name
            const namesCount = data.n_count
            names.forEach((item, index) => {
                let tep = [item].concat(data.corr[item])
                let obj = {key: index, serial: index + 1, count: namesCount[item]}
                let colObj = []
                let cl = [{title: '序号', dataIndex: 'serial', key: '0', width: 80}]

                tep.forEach((items, ind) => {

                    ind === 0 ? obj['name'] =items : obj[`number${ind}`] = items
                    if (ind === 0) {
                        cl.push({
                            [`title`]: '名称',
                            [`key`]: ind + 1,
                            [`dataIndex`]: 'name',
                            [`width`]: 200
                        })
                    } else {
                        cl.push({
                            [`title`]: `${ind}`,
                            [`key`]: ind + 1,
                            [`dataIndex`]: `number${ind}`,
                            render: (r, t, index) => {
                                let res = ``
                                if (r) {
                                    if (r === 1) {
                                        res = <span className={``}>{r ? r : '--'}</span>
                                    } else if (r < 0.3) {
                                        res = <span className={`table_td_bg_green`}>{r ? parseFloat(r).toFixed(4) : '--'}</span>
                                    } else if (r > 0.8){
                                        res = <span className={`table_td_bg_red`}>{r ?  parseFloat(r).toFixed(4)  : '--'}</span>
                                    } else {
                                        res = <span className={``}>{r ? parseFloat(r).toFixed(4) : '--'}</span>
                                    }
                                } else {
                                    res = <span className={``}>{r ? parseFloat(r).toFixed(4) : '--'}</span>
                                }

                                if (t.count < 30) {
                                    res = <Tooltip title={`净值条数少于30条！`}>{res}</Tooltip>
                                }
                                return res
                            }
                        })
                    }

                    colObj.concat(cl)
                })
                cols.push(cl)
                dataSource.push(obj)
            })

            if(dataSource.length > 0) {
                await this.setState({corColumns: cols[0], corData: dataSource})
            }
        }
    }

    async getHistoryInvestData(params) {
        const baseParams = { indicator: "return", rankType: '2',  fundId: "JR000001"}
        params = Object.assign(baseParams, params)
        const data = await _getHistoryInvest(params)
        if (data) {
            const source = []
            data.forEach((item, index) => {
                source.push({
                    key: index,
                    first: item.column0 ? item.column0 : '--',
                    year: item.column1 ? item.column1 : '--',
                    one: item.column2 ? item.column2 : '--',
                    three: item.column3 ? item.column3 : '--',
                    six: item.column4 ? item.column4 : '--',
                    firstYear: item.column5 ? item.column5 : '--',
                    secondYear: item.column6 ? item.column6 : '--',
                })
            })
            this.setState({ investData: source })
        }
        const newParam = {c_rank_type: '2', fund_id: 'JR000001', token: "88d34ede-9302-4b5a-8701-4e940d425d9b" }
        const rankData = await _getRankingData(newParam)
        this.setState({rankData: rankData})
    }

    // 历史收益能力查询条件
    createSelect() {
        const { rankType, indicator } = this.state;
        return (
        <div className='float_right'>
            <Select value={indicator} style={{width: '140px', marginRight: '10px'}} placeholder='收益能力' onChange={this.indicator.bind(this)} >
            <Option value="return">收益能力</Option>
            <Option value="sharpe_a">风险控制能力</Option>
            <Option value="max_drawdown">回撤控制能力</Option>
            </Select>
            <Select style={{width: '140px', marginRight: '10px'}} value={rankType} placeholder='全市场' onChange={this.rankType.bind(this)}>
            <Option value="2">全市场</Option>
            <Option value="3">汇升核心池投顾</Option>
            <Option value="1">同策略排名</Option>
            </Select>
        </div>
        )
    }
  
   
    render() {
        
        return (
            <div className={detailsStyle.Performance}>
            <PerformanceSearch getHeadSecData={this.getHeadSecData.bind(this)} />
            <div className={detailsStyle.charts_item_bg}>
                <HeaderTitle iconStatus={false} title={`收益走势图`} checkStatus={true} changeStatus={this.changeCheckStatus.bind(this)} exportFiles={this.exportExcelFiles.bind(this)}/>
                <CommonCharts idName='lineChart' ref='lineChart' styles={{width: '100%', height: '600px'}} />
            </div>
            <div className={`${detailsStyle.charts_item_bg} mt_20`}>
                <HeaderTitle iconStatus={false} title={`回撤走势图`} exportFiles={this.exportExcelFiles.bind(this)}/>
                <CommonCharts ref='areaChart' idName='areaChart' styles={{width: '100%', height: '600px'}} />
            </div>
            <div className={`${detailsStyle.charts_item_bg} mt_20`}>
                <HeaderTitle iconStatus={false} title={`收益-风险指标`} exportFiles={this.exportExcelFiles.bind(this)}/>
                <RiskTable dataSource={this.state.dataSource} valueChange={this.riskTable.bind(this)} sharpeChange={this.sharpeChange.bind(this)} />
            </div>
            <div className={`${detailsStyle.charts_item_bg} mt_20`}>
                <HeaderTitle iconStatus={false} title={`月度收益率`} exportFiles={this.exportExcelFiles.bind(this)} />
                {/* <MonthTable monthData={this.state.monthData} /> */}
                <Table columns={monthColumns} dataSource={this.state.monthData} pagination={false} />
            </div>
            <div className={`${detailsStyle.charts_item_bg} mt_20`}>
                <HeaderTitle iconStatus={false} title={`周收益率分布`}exportFiles={this.exportExcelFiles.bind(this)} />
                <CommonCharts idName='weekCharts' ref='weekCharts' styles={{width: '100%', height: '600px'}}/>
            </div>
            <div className={`${detailsStyle.charts_item_bg} mt_20`}>
                <HeaderTitle iconStatus={false} title={`产品相关性`} exportFiles={this.exportExcelFiles.bind(this)} />
                <div className={`clear-fix ${detailsStyle.correlation}`}>
                    <div className={`float_left ${detailsStyle.correlation_item}`}>
                        <div className={`float_right `} id={`cascader_product_corr`}>
                                <Select style={{ width: '600px' }} mode="tags" maxTagCount={6} value={this.state.defaultCorrelation} onChange={this.multipleSelect.bind(this)} value={this.state.defaultCorrelation} placeholder={`选择比较基准`}>
                                {this.state.selectData.map((item) => <Option key={item.benchmark_id} value={item.benchmark_id}>{item.benchmark_name}</Option>)}
                            </Select>
                        </div>
                        <CommonCharts idName='correlationCharts' ref='correlation' styles={{width: '100%', height: '500px', marginTop: 30}} />
                    </div>
                        <div className={`float_right ${detailsStyle.correlation_item}`}>
                        <div className={`align_right`}>
                            <Button type='primary' onClick={this.addModal.bind(this)}><Icon type='plus' className={'product_common_header_plus'} />添加对比产品</Button>
                        </div>
                        <Table className={`${detailsStyle.correlation_table_performance} mt_20`} columns={this.state.corColumns} dataSource={this.state.corData} pagination={false} />
                        <AddCompanyModal ref='addCompanyPro' />
                    </div>
                </div>
            </div>
            <div className={`${detailsStyle.charts_item_bg} mt_20`}>
                <HeaderTitle iconStatus={true} title={`历史收益能力`} children={this.createSelect()} />
                <div className={`clear-fix ${detailsStyle.correlation}`}>
                    <div className={`float_left ${detailsStyle.correlation_item}`}>
                        <HeaderTitle iconStatus={false} title={`历史投资能力`} isBorder={true} exportFiles={this.exportExcelFiles.bind(this)}/>
                        <Table columns={historyColumns} dataSource={this.state.investData} pagination={false} />
                    </div>
                    <div className={`float_right ${detailsStyle.correlation_item}`}>
                        <HeaderTitle iconStatus={false} title={`历年排名`} isBorder={true} exportFiles={this.exportExcelFiles.bind(this)} />
                        <Table columns={rankColumns} dataSource={this.state.rankData} pagination={false} />
                    </div>
                </div>
            </div>
        </div>
        )
    }
}